import React from 'react'
import {connect} from 'react-redux'
import { Form, Select, message, Switch, Button, Alert, Spin } from 'antd';
import {messages} from "share/common";
import Condition from "components/condition";
import docTemplateService from "containers/financial-account/doc-template/doc-template-service";
const If = Condition.If;
const FormItem = Form.Item;
const Option = Select.Option;
const formItemLayout = {
  labelCol: {span: 8},
  wrapperCol: {span: 14},
};

class validateRule extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      record: {},
      ruleNameList: [],
      allList: [],
      saveLoading: false,
      ruleID: '',
      validate: 0,
      setOfBooksId: '',
      loading: false
    }
  }

  getList = () => {
    const { setOfBooksId, editRecord } = this.props;
    this.setState({loading: true});
    Promise.all([
      docTemplateService.getRuleNameList(),
      docTemplateService.getAllList(setOfBooksId),
      editRecord.id && docTemplateService.getValidateDetail(editRecord.id)
    ]).then(res => {
      this.setState({
        ruleNameList: res[0].data,
        loading: false,
        allList: res[1].data
      });
    }).catch(() => {
      this.setState({loading: false});
      message.error(messages('financial-account.key15')/*系统异常*/);
    });
  };

  componentWillReceiveProps(nextProps) {
    if (nextProps.showSlideFrame === this.props.showSlideFrame)
      return;
    if (!nextProps.showSlideFrame) {
      this.props.form.resetFields();
      return !1;
    }
    this.props.form.resetFields();
    this.setState({
      record: nextProps.editRecord,
      setOfBooksId: nextProps.setOfBooksId
    },() => {
      this.getList();
      const { record } = this.state;
      if(record.journalRuleDetailId){
        this.setState({loading: true});
        docTemplateService.getValidateDetail(record.journalRuleDetailId).then(res => {
          this.setState({
            record: res ? res.data : {},
            validate: res ? res.data.dcEqualType : 0,
            ruleID: res ? res.data.journalRuleId : '',
            loading: false
          });
        }).catch(e => {
          this.setState({loading: false});
          message.error(e.response.data.message);
        })
      } else {
        this.setState({validate: 0, ruleID: ''})
      }
    });
  }

  handleSave = () => {
    this.props.form.validateFieldsAndScroll((err,values) => {
      if(!err){
        const { record, setOfBooksId } = this.state;
        const { user } = this.props;
        record.id && (values.id = record.id);
        values.setOfBooksId = setOfBooksId;
        let name = Object.keys(record).length > 0 ? 'updateValidate' : 'addValidate';
        this.setState({saveLoading: true});
        docTemplateService[name](values,user.userOID).then(() => {
          this.setState({saveLoading: false});
          this.props.close(true);
        }).catch(e => {
          this.setState({saveLoading: false});
          message.error(e.response.data.message);
        })
      }
    })
  };

  handleChangeRule = (value) => {
    this.setState({ruleID: value});
  };

  handleChangeValidate = (value) => {
    this.setState({validate: Number(value)});
  };

  render(){
    const { record, ruleNameList, allList, saveLoading, ruleID, validate, loading } = this.state;
    const { getFieldDecorator } = this.props.form;
    return(
      <div>
        <Spin spinning={loading}>
          <Form style={{marginTop: '10px'}}>
            <FormItem label={messages('financial-account.key25')/*规则名称*/} {...formItemLayout}>
              {getFieldDecorator('journalRuleId', {
                rules: [{
                  required: true, message: messages('common.please.select')/*请选择*/,
                }],
                initialValue: record.journalRuleId
              })(
                <Select placeholder={messages('common.please.select')/*请选择*/}
                        disabled={record.journalRuleId ? true : false} onChange={this.handleChangeRule}>
                  {
                    ruleNameList.map(item => {
                      return <Option key={item.id} title={item.ruleName}>{item.ruleName}</Option>
                    })
                  }
                </Select>
              )}
            </FormItem>
            <FormItem label={messages('common.column.status')/*状态*/} {...formItemLayout}>
              {getFieldDecorator('isEnable', {
                initialValue: typeof record.isEnable === "boolean" ? record.isEnable : false,
                valuePropName: 'checked'
              })(
                <Switch/>
              )}
            </FormItem>
            <If value={ruleID === '1104980859250810881'}>
              <div>
                <Alert showIcon type='info' message={messages('financial-account.key28')/*借贷相等仅校验本币金额相等；*/} style={{marginTop: '-10px'}}/>
                <div style={{borderBottom: '1px solid #e1e1e1', margin: '15px -15px 15px'}}/>
                <FormItem label={messages('financial-account.key29')/*公司平衡校验*/} {...formItemLayout}>
                  {getFieldDecorator('companyBalanceType', {
                    rules: [{
                      required: true, message: messages('common.please.select')/*请选择*/,
                    }],
                    initialValue: record.companyBalanceType ? String(record.companyBalanceType) : undefined
                  })(
                    <Select placeholder={messages('common.please.select')/*请选择*/}>
                      <Option key={1001} title={messages('financial-account.key30')/*公司内校验*/}>{messages('financial-account.key30')/*公司内校验*/}</Option>
                      <Option key={1002} title={messages('financial-account.key31')/*公司间校验*/}>{messages('financial-account.key31')/*公司间校验*/}</Option>
                    </Select>
                  )}
                </FormItem>
                <FormItem label={messages('financial-account.key32')/*借贷相等校验*/} {...formItemLayout}>
                  {getFieldDecorator('dcEqualType', {
                    rules: [{
                      required: true, message: messages('common.please.select')/*请选择*/,
                    }],
                    initialValue: record.dcEqualType ? String(record.dcEqualType) : undefined
                  })(
                    <Select placeholder={messages('common.please.select')/*请选择*/} onChange={this.handleChangeValidate}>
                      <Option key={1001} title={messages('financial-account.key33')/*借贷方向-金额组合校验*/}>{messages('financial-account.key33')/*借贷方向-金额组合校验*/}</Option>
                      <Option key={1002} title={messages('financial-account.key34')/*借/贷方金额校验*/}>{messages('financial-account.key34')/*借/贷方金额校验*/}</Option>
                    </Select>
                  )}
                </FormItem>
              </div>
            </If>
            {Number(validate) === 1001 && (
              <div>
                <div style={{borderBottom: '1px solid #e1e1e1', margin: '-10px -15px 20px'}}/>
                <FormItem label={messages('financial-account.key35')/*借贷方向*/} {...formItemLayout}>
                  {getFieldDecorator('dcId', {
                    rules: [{
                      required: true, message: messages('common.please.select')/*请选择*/,
                    }],
                    initialValue: record.dcId
                  })(
                    <Select placeholder={messages('common.please.select')/*请选择*/}>
                      {
                        allList.map(item => {
                          return !item.curingField ? <Option key={item.id} title={`${item.ledgerName}(${item.ledgerCode})`}>{`${item.ledgerName}(${item.ledgerCode})`}</Option> : ''
                        })
                      }
                    </Select>
                  )}
                </FormItem>
                <FormItem label={messages('financial-account.key36')/*原币金额*/} {...formItemLayout}>
                  {getFieldDecorator('amountId', {
                    initialValue: record.amountId
                  })(
                    <Select placeholder={messages('common.please.select')/*请选择*/} allowClear>
                      {
                        allList.map(item => {
                          return !item.curingField ? <Option key={item.id}
                                         title={`${item.ledgerName}(${item.ledgerCode})`}>{`${item.ledgerName}(${item.ledgerCode})`}</Option> : ''
                        })
                      }
                    </Select>
                  )}
                </FormItem>
                <FormItem label={messages('financial-account.key37')/*本币金额*/} {...formItemLayout}>
                  {getFieldDecorator('baseAmountId', {
                    rules: [{
                      required: true, message: messages('common.please.select')/*请选择*/,
                    }],
                    initialValue: record.baseAmountId
                  })(
                    <Select placeholder={messages('common.please.select')/*请选择*/}>
                      {
                        allList.map(item => {
                          return !item.curingField ? <Option key={item.id}
                                         title={`${item.ledgerName}(${item.ledgerCode})`}>{`${item.ledgerName}(${item.ledgerCode})`}</Option> : ''
                        })
                      }
                    </Select>
                  )}
                </FormItem>
              </div>
            )}
            {Number(validate) === 1002 && (
              <div>
                <div style={{borderBottom: '1px solid #e1e1e1', margin: '-10px -15px 20px'}}/>
                <FormItem label={messages('financial-account.key38')/*借方原币金额*/} {...formItemLayout}>
                  {getFieldDecorator('debitAmountId', {
                    initialValue: record.debitAmountId
                  })(
                    <Select placeholder={messages('common.please.select')/*请选择*/} allowClear>
                      {
                        allList.map(item => {
                          return <Option key={item.id}
                                         title={`${item.ledgerName}(${item.ledgerCode})`}>{`${item.ledgerName}(${item.ledgerCode})`}</Option>
                        })
                      }
                    </Select>
                  )}
                </FormItem>
                <FormItem label={messages('financial-account.key39')/*借方本币金额*/} {...formItemLayout}>
                  {getFieldDecorator('debitBaseAmountId', {
                    rules: [{
                      required: true, message: messages('common.please.select')/*请选择*/,
                    }],
                    initialValue: record.debitBaseAmountId
                  })(
                    <Select placeholder={messages('common.please.select')/*请选择*/}>
                      {
                        allList.map(item => {
                          return <Option key={item.id}
                                         title={`${item.ledgerName}(${item.ledgerCode})`}>{`${item.ledgerName}(${item.ledgerCode})`}</Option>
                        })
                      }
                    </Select>
                  )}
                </FormItem>
                <FormItem label={messages('financial-account.key40')/*贷方原币金额*/} {...formItemLayout}>
                  {getFieldDecorator('creditAmountId', {
                    initialValue: record.creditAmountId
                  })(
                    <Select placeholder={messages('common.please.select')/*请选择*/} allowClear>
                      {
                        allList.map(item => {
                          return <Option key={item.id}
                                         title={`${item.ledgerName}(${item.ledgerCode})`}>{`${item.ledgerName}(${item.ledgerCode})`}</Option>
                        })
                      }
                    </Select>
                  )}
                </FormItem>
                <FormItem label={messages('financial-account.key41')/*贷方本币金额*/} {...formItemLayout}>
                  {getFieldDecorator('creditBaseAmountId', {
                    rules: [{
                      required: true, message: messages('common.please.select')/*请选择*/,
                    }],
                    initialValue: record.creditBaseAmountId
                  })(
                    <Select placeholder={messages('common.please.select')/*请选择*/}>
                      {
                        allList.map(item => {
                          return <Option key={item.id}
                                         title={`${item.ledgerName}(${item.ledgerCode})`}>{`${item.ledgerName}(${item.ledgerCode})`}</Option>
                        })
                      }
                    </Select>
                  )}
                </FormItem>
              </div>
            )}
          </Form>
        </Spin>
        <div className="footer-operate" style={{backgroundColor:'#ffffff',left:'0px'}}>
          <Button type="primary"  onClick={this.handleSave} style={{margin:'0px 10px'}} loading={saveLoading}>{messages('common.save')/*保存*/}</Button>
          <Button onClick={this.props.close}>{messages('common.cancel')/*取消*/}</Button>
        </div>
      </div>
    )
  }
}

function mapStateToProps(state){
  return {
    user: state.login.user
  }
}

const wrappedValidateRule = Form.create()(validateRule);
export default connect(mapStateToProps)(wrappedValidateRule);
